package com.hxzy.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxzy.yygh.common.exception.YyghException;
import com.hxzy.yygh.common.helper.JwtHelper;
import com.hxzy.yygh.common.result.ResultCodeEnum;
import com.hxzy.yygh.enums.AuthStatusEnum;
import com.hxzy.yygh.model.user.Patient;
import com.hxzy.yygh.model.user.UserInfo;
import com.hxzy.yygh.user.mapper.UserInfoMapper;
import com.hxzy.yygh.user.service.PatientService;
import com.hxzy.yygh.user.service.UserInfoService;
import com.hxzy.yygh.vo.user.LoginVo;
import com.hxzy.yygh.vo.user.UserAuthVo;
import com.hxzy.yygh.vo.user.UserInfoQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private PatientService patientService;

    //用户手机登录
    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        //从loginVo过去输入的手机号
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();

        //判断手机号和验证码是否为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            throw new YyghException(ResultCodeEnum.FETCH_USERINFO_ERROR);
        }

        //判断手机号和输入验证码是否一致
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(redisCode)){
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }

        //判断是否绑定手机号、绑定手机号码
        UserInfo userInfo = null;
        if(!StringUtils.isEmpty(loginVo.getOpenid())) {
            userInfo = this.selectWxInfoOpenId(loginVo.getOpenid());
            if(null != userInfo) {
                userInfo.setPhone(loginVo.getPhone());
                //执行更新操作
                this.updateById(userInfo);
            } else {
                throw new YyghException(ResultCodeEnum.DATA_ERROR);
            }
        }

        if(userInfo == null){
            //判断是否为第一次登录：根据手机号查询数据库，如果不存在相同的手机号就是第一次登录 ===>注册
            LambdaQueryWrapper<UserInfo> userInfoLqw = new LambdaQueryWrapper<>();
            userInfoLqw.eq(UserInfo::getPhone, phone);
            userInfo = baseMapper.selectOne(userInfoLqw);
            if(userInfo == null){
                //添加新用户信息到数据库
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
        }

        //不是第一次，直接登录
        //判断用户账号状态
        if (userInfo.getStatus() == 0){
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }

        //获取用户页面显示名称
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)){
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)){
            name = userInfo.getPhone();
        }

        //获取用户token
        String token = JwtHelper.createToken(userInfo.getId(), name);

        //封装信息
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("name", name);
        resultMap.put("token", token);

        //返回用户信息
        return resultMap;
    }

    //根据openid,获取用户信息
    @Override
    public UserInfo selectWxInfoOpenId(String openid) {
        LambdaQueryWrapper<UserInfo> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserInfo::getOpenid,openid);
        return baseMapper.selectOne(lqw);
    }

    //用户认证接口
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据id查询对象
        UserInfo userInfo = baseMapper.selectById(userId);

        //封装认证属性
        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());

        //更新用户信息
        baseMapper.updateById(userInfo);
    }

    //传入分页对象、条件参数对象，返回符合条件分页的用户分页结果
    @Override
    public IPage<UserInfo> getByPageAndCondition(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        //1.获取具体条件值
            //获取关键字
            String keyword = userInfoQueryVo.getKeyword();
            //获取用户状态
            Integer status = userInfoQueryVo.getStatus();
            //获取用户认证状态
            Integer authStatus = userInfoQueryVo.getAuthStatus();
            //获取创建时间
            String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
            //获取结束时间
            String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();

        //2.对条件值进行非空判断
        LambdaQueryWrapper<UserInfo> lqw = new LambdaQueryWrapper<>();
            //判断关键字
            lqw.like(keyword != null, UserInfo::getName, keyword);
            //判断用户状态
            lqw.eq(status != null, UserInfo::getStatus, status);
            //判断认证状态
            lqw.eq(authStatus !=null, UserInfo::getAuthStatus, authStatus);
            //判断创建时间
            lqw.ge(createTimeBegin != null, UserInfo::getCreateTime, createTimeBegin);
            //判断结束时间
            lqw.le(createTimeEnd != null, UserInfo::getCreateTime, createTimeEnd);

        //3.调用page方法，并传入条件
        Page<UserInfo> userInfoPage = baseMapper.selectPage(pageParam, lqw);

        //4.编码处理(编码  ==> 中文)
        userInfoPage.getRecords().stream().forEach(item ->{
            this.packageUserInfo(item);
        });

        //5.返回分页结果
        return userInfoPage;
    }

    //用户锁定-解锁 方法
    @Override
    public void updateStatus(Long id, Integer status) {
        if(status == 1 || status == 0){
            UserInfo userInfo = baseMapper.selectById(id);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }

    //获得用户详情信息
    @Override
    public Map<String, Object> showUserInfoByUserId(Long userId) {
        //根据用户id获取用户信息
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));

        //更具用户id获取对应就诊人信息
        List<Patient> patientList = patientService.getPatientList(userId);

        //封装参数
        Map<String,Object> map = new HashMap<>();
        map.put("userInfo", userInfo);
        map.put("patientList", patientList);

        //返回封装好参数的map集合
        return map;
    }

    //用户认证审批
    @Override
    public void authUser(Long id, Integer authStatus) {
        if (authStatus == 2 || authStatus == -1){
            UserInfo userInfo = baseMapper.selectById(id);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    //编码处理(编码  ==> 中文)
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //用户认证状态中文名称存入param属性
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //用户状态中文名称存入param属性
        userInfo.getParam().put("statusString", userInfo.getStatus() == 0 ? "锁定" : "正常");
        return userInfo;
    }
}
